package com.andatsoft.laisim.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.andatsoft.laisim.R;
import com.andatsoft.laisim.asynctask.SongScanner;
import com.andatsoft.laisim.config.LaisimConfig;
import com.andatsoft.laisim.db.DataBaseAccess;
import com.andatsoft.laisim.service.PlayerService;
import com.andatsoft.laisim.service.PlayerService.RepeatMode;
import com.andatsoft.laisim.theme.ThemeManager;
import com.andatsoft.laisim.utils.Common;
import com.andatsoft.laisim.view.WPProgressBar;

public class WelcomeActivity extends BaseActivity {
	public static boolean isLoaded;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Intent i = getIntent();
		if (i.getAction() != null && i.getAction().equals(Intent.ACTION_VIEW)) {
			Intent intent = new Intent(WelcomeActivity.this,
					MiniPlayerActivity.class);
			intent.putExtra(Common.INTENT_DATA_SONG_URI, i.getDataString());
			startActivity(intent);
			overridePendingTransition(R.anim.fade_in_fast, R.anim.fade_out_fast);
			WelcomeActivity.this.finish();
		} else {
			setContentView(R.layout.activity_welcome);
			setAlpha((FrameLayout) findViewById(R.id.layout_welcome), 0.8f);
			overridePendingTransition(R.anim.fade_in_fast, R.anim.fade_out_fast);
			new InitResourceTask().execute();
		}
	}

	/**
	 * @author Ngoc Dat
	 * 
	 *         This task will load all resource for the player: theme, skin...
	 * 
	 */
	class InitResourceTask extends AsyncTask<Void, Void, Boolean> {

		@Override
		protected Boolean doInBackground(Void... params) {
			boolean re = false;
			// load theme
			re = ThemeManager.loadTheme(getApplicationContext());
			// load config
			SharedPreferences sp = getSharedPreferences(Common.SP_CONFIG_NAME,
					Context.MODE_PRIVATE);

			LaisimConfig.isEqEnable = sp.getBoolean(Common.SP_CONFIG_EQ, false);
			LaisimConfig.isBassEnable = sp.getBoolean(Common.SP_CONFIG_BASS,
					false);
			LaisimConfig.isShuffle = sp.getBoolean(Common.SP_CONFIG_SHUFFLE,
					false);
			int rePepeat = sp.getInt(Common.SP_CONFIG_REPEAT, 0);
			RepeatMode reP = rePepeat == 0 ? RepeatMode.NONE
					: (rePepeat == 1 ? RepeatMode.REPEAT_ONE
							: RepeatMode.REPEAT_ALL);
			LaisimConfig.repeatMode = reP;
			LaisimConfig.playingSongId = sp.getInt(
					Common.SP_CONFIG_PLAY_SONG_ID, 0);
			LaisimConfig.playingSongIndex = sp.getInt(
					Common.SP_CONFIG_PLAY_SONG_INDEX, 0);
			LaisimConfig.currentDuration = sp.getInt(
					Common.SP_CONFIG_CURRENT_DURATION, 0);
			re = ThemeManager.loadSkin(getApplicationContext(),
					ThemeManager.MAIN_ACTIVYTY);
			SharedPreferences.Editor ed = sp.edit();
			ed.putBoolean(Common.SP_CONFIG_IS_LOADED, true);
			ed.commit();
			return re;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			isLoaded = true;
			if (result) {
				int launchTime = getLaunchTime();
				if (launchTime <= 0) {
					// This is the first time
					new MainSongScanner(getApplicationContext(), true)
							.execute();
				} else {
					DataBaseAccess db = DataBaseAccess
							.getInstance(getApplicationContext());
					if (db.getAllSong().size() < 1) {
						// Rescan songs
						new MainSongScanner(getApplicationContext(), true)
								.execute();
					} else {
						Intent i = new Intent(WelcomeActivity.this,
								PlayerService.class);
						i.putExtra(PlayerService.INTENT_SERVICE_COMMAND,
								PlayerService.SERVICE_COMMAND_MAIN_ACTIVITY);
						startService(i);
						((WPProgressBar) findViewById(R.id.progress_welcome))
								.setVisibility(View.GONE);
						Intent intent = new Intent(WelcomeActivity.this,
								MainActivity.class);
						intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
						startActivity(intent);
						WelcomeActivity.this.finish();
					}
				}
				updateLaunchTime(++launchTime);

			} else {
				Toast.makeText(getApplicationContext(),
						"Error when loading resource.", Toast.LENGTH_LONG)
						.show();
			}

		}

		private int getLaunchTime() {
			SharedPreferences sp = getSharedPreferences(Common.SP_MAIN_NAME,
					MODE_PRIVATE);
			return sp.getInt(Common.SP_MAIN_LAUNCH_TIME, 0) < 0 ? 0 : sp
					.getInt(Common.SP_MAIN_LAUNCH_TIME, 0);
		}

		private void updateLaunchTime(int time) {
			SharedPreferences sp = getSharedPreferences(Common.SP_MAIN_NAME,
					MODE_PRIVATE);
			SharedPreferences.Editor editor = sp.edit();

			editor.putInt(Common.SP_MAIN_LAUNCH_TIME, time);
			editor.commit();
		}
	}

	class MainSongScanner extends SongScanner {

		public MainSongScanner(Context c, boolean isFullScan) {
			super(c, isFullScan);
		}

		@Override
		protected Integer[] doInBackground(String[]... params) {
			return super.doInBackground(params);
		}

		@Override
		protected void onPostExecute(Integer[] result) {
			isLoaded = true;
			((WPProgressBar) findViewById(R.id.progress_welcome))
					.setVisibility(View.GONE);
			Intent i = new Intent(WelcomeActivity.this, PlayerService.class);
			i.putExtra(PlayerService.INTENT_SERVICE_COMMAND,
					PlayerService.SERVICE_COMMAND_MAIN_ACTIVITY);
			startService(i);
			Intent intent = new Intent(WelcomeActivity.this, MainActivity.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
			startActivity(intent);
			WelcomeActivity.this.finish();
		}
	}
}
